package com.bsoft.gol.hcs.utils;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * 时间工具类 除了私信使用getMessageTime外，其他都使用getDateTime方法
 * <p>
 * 传过来的long都是UTC时间
 *
 * @author
 */
public class DateUtil {

    public static String tmepReturnStr = "不祥";
    public static DateFormat format = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    public static DateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日");
    public static DateFormat format2 = new SimpleDateFormat("yyyy年MM月");
    public static DateFormat format3 = new SimpleDateFormat("yyyy-MM-dd");
    public static DateFormat format4 = new SimpleDateFormat("MM-dd");
    public static DateFormat format5 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static DateFormat format6 = new SimpleDateFormat("yyyyMMddHHmmss");
    public static Calendar cal = Calendar.getInstance();

    public static String getDateTime(long d) {
        String result = "";
        if (d > 0) {
            result = getString(new Date(d));
        }
        return result;
    }


    public static int getAge(long bityhday) {
        Date d1 = new Date(bityhday + cal.get(Calendar.ZONE_OFFSET));
        Date d2 = new Date();
        return d2.getYear() - d1.getYear();
    }

    public static long getTime(String s) {
        try {
            Date d1 = format3.parse(s);
            return d1.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    // 无法选择未来时间，≤now
    public static boolean check(String d) {
        try {
            Date d1 = format3.parse(d);
            Date d2 = format3.parse(format3.format(new Date()));
            return d2.getTime() >= d1.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 把字符串转化成日期型。
     *
     * @param birthdayString
     *            字符串
     * @param defaultValue
     *            日期格式
     * @return Date 转化后的日期
     */
    public static Date getDate(String birthdayString, Date defaultValue) {
        return getDate(birthdayString, "yyyy-MM-dd", defaultValue);
    }

    /**
     * 把字符串转化成日期型。
     *
     * @param name
     *            字符串
     * @param df
     *            日期格式
     * @return Date 转化后的日期
     */
    public static Date getDate(String name, String df, Date defaultValue) {
        if (name == null) {
            return defaultValue;
        }

        SimpleDateFormat formatter = new SimpleDateFormat(df);

        try {
            return formatter.parse(name);
        } catch (ParseException e) {
        }

        return defaultValue;
    }

    public static Date getNextDay(){
        Calendar calendar=Calendar.getInstance();
        Date date=new Date();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY,calendar.get(Calendar.HOUR_OF_DAY)+1);
        return calendar.getTime();
    }

    /**
     * 把字符串转化成日期型。 缺省为当前系统时间。
     *
     * @param birthdayString
     *            字符串
     */
    public static Date getDate(String birthdayString) {
        return getDate(birthdayString, null);
    }



    public static String getDateTime1(long d) {
        String result = "";
        if (d > 0) {
            result = getString(new Date(d));
        }
        return result;
    }

    // 传过来的不是UTC时间
    public static String getNewHongDongDay(long d) {
        return format1.format(new Date(d));
    }

    // 返回当前的UTC时间
    public static long getNowTime() {
        return System.currentTimeMillis()
                - cal.get(Calendar.ZONE_OFFSET);
    }

    public static long getUtcTimeByStr(String str) {
        try {
            return format3.parse(str).getTime()
                    - cal.get(Calendar.ZONE_OFFSET);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static String getBirthDateTime(long d) {
        return format3.format(new Date(d
                + cal.get(Calendar.ZONE_OFFSET)));
    }

    public static String getDateTime(DateFormat format, long d) {
        return format.format(new Date(d));
    }

    public static String getDateTime(String format, long d) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(d));
    }

    public static Date getDateTime(String formate, String d) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(formate);
            return sdf.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Date getDateTime(DateFormat formate, String d) {
        try {
            return formate.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String dateFormate(Date date, String formate) {
        if (date != null) {
            SimpleDateFormat sdf = new SimpleDateFormat(formate);
            return sdf.format(date);
        } else {
            return null;
        }

    }

    // public static Date getSodaoDateByString(String d) throws ParseException {
    // format.setTimeZone(TimeZone.getTimeZone("UTC"));
    // return format.parse(d);
    // }

    /**
     * 0秒-60秒内显示“刚刚” 1分钟-2分钟内显示“1分钟前” 1小时-2小时内显示“1小时前” 1天-2天内显示“1天前”
     * 7天-14天显示“1周前” 30天-60天显示1月前 之后已月类推计算 ）
     */
    public static String getString(Date date) {
        long curTime = System.currentTimeMillis();

        long diffSecond = 0L;
        long diffDay = 0L;
        diffSecond = (curTime - date.getTime()) / 1000L;

        if (diffSecond >= 86400) {// 两个相差
            Calendar curDate = new GregorianCalendar();
            curDate.setTime(new Date(curTime));
            curDate.set(Calendar.HOUR_OF_DAY, 23);
            curDate.set(Calendar.MINUTE, 59);
            curDate.set(Calendar.SECOND, 59);
            curDate.set(Calendar.MILLISECOND, 999);
            diffDay = (curDate.getTimeInMillis() - date.getTime()) / 86400000L;
            if (diffDay <= 30) {
                return diffDay + "天前";
            } else {
                if (date.getYear() == new Date().getYear()) {
                    return format4.format(new Date(date.getTime()
                            + cal.get(Calendar.ZONE_OFFSET)));
                } else {
                    return getBirthDateTime(date.getTime());
                }
            }
        } else {
            if (diffSecond < 0) {
                return "刚刚";
            } else if (diffSecond < 60) {
                return "刚刚";
            } else if (diffSecond < 3600) {
                return diffSecond / 60 + "分钟前";
            } else if (diffSecond < 86400) {
                return diffSecond / 3600 + "小时前";
            }
        }
        return "...";
    }

    public static long getDayTime(String d) {
        try {
            return format1.parse(d).getTime()
                    - cal.get(Calendar.ZONE_OFFSET);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public static long getMonthTime(String d) {
        try {
            return format2.parse(d).getTime()
                    - cal.get(Calendar.ZONE_OFFSET);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

//    public static void main(String args[]) throws ParseException {
//        System.out.println(getHenceforthTimeString(30));
////        System.out.println(getNowString());
////		System.out.println(dateFormate(new Date(1448504072862l), "yyyy-MM-dd HH:mm:ss"));
////		System.out.println(dateFormate(new Date(1448504072866l), "yyyy-MM-dd HH:mm:ss"));
////		Date date = new Date();
////		Date date2 = DateUtils.parseDate("1994-03-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
////
////		System.out.println(getAge(date2));
//    }


    /**
     * 格式化时间
     * 如果没有传参就默认 当前时间  默认yyyy-MM-dd HH:mm:ss 格式
     *
     * @param date   时间
     * @param format 格式
     * @return 格式化后的时间
     */
    public static String formDate(Date date, String format) {
        if (CommonUtils.isEmpty(format)) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        if (date == null) {
            date = new Date();
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        return dateFormat.format(date);
    }


    /**
     * 根据指定时间获取年龄
     *
     * @param date
     * @return
     */
    public static Integer getAge(Date date) {
        if(null != date){
            Date now = new Date();

            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(now);

            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date);

            return cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
        }

        return 0;
    }

    /**
     * 根据指定时间获取当前差额时间
     *
     * @param date
     * @return
     */
    public static Long getSeconds(Date date) {
        Date now = new Date();

        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(now);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date);

        long c1 = cal1.getTimeInMillis();
        long c2 = cal2.getTimeInMillis();

        return (c1-c2)/1000;
    }


    /**
     * 根据指定时间获取当前差额时间
     *
     * @param date
     * @return
     */
    public static Long getSecondsByexpire(Date date) {
        Date now = new Date();

        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(now);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date);

        long c1 = cal1.getTimeInMillis();
        long c2 = cal2.getTimeInMillis();
        if(c2<= c1){
            return 0L;
        }else{
            return (c2-c1)/1000;
        }
    }

    /**
     *  获取yyyyMMddHHmmss格式的当前时间
     * @return
     */
    public static String getNowString(){
        return format6.format(new Date());
    }
    /**
     *  获取N天后的yyyyMMddHHmmss格式的时间
     * @return
     */
    public static String getHenceforthTimeString(int day){
        Calendar now =Calendar.getInstance();
        now.setTime(new Date());
        now.set(Calendar.DATE,now.get(Calendar.DATE)+day);
        return format6.format(now.getTime());
    }

    /**
     *  获取yyyy-MM-dd HH:mm:ss格式的当前时间
     * @return
     */
    public static String getNowStr(){
        return format5.format(new Date());
    }

    /**
     *  yyyyMMddHHmmss时间转换为yyyy-MM-dd HH:mm:ss格式的时间
     * @return
     */
    public static String getStrTime(String date){
        try {
            return format5.format(format6.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return getNowStr();
    }

    public static long getDerTime(Date str, Date end){
            return end.getTime() - str.getTime();

    }

    public static Calendar getDayBegin(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar;
    }

    public static Calendar getDayEnd(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 59);
        return calendar;
    }


    public static int getAgeByBirth(Date birthday){
        int age = 0;
        try {
            Calendar cal = Calendar.getInstance();
            Calendar bir = Calendar.getInstance();
            bir.setTime(birthday);
            if(cal.before(birthday)){
                throw new IllegalArgumentException("The birthday is before Now,It's unbelievable");
            }

            int yearNow = cal.get(Calendar.YEAR);
            int monthNow = cal.get(Calendar.MONTH);
            int dayNow = cal.get(Calendar.DAY_OF_MONTH);

            int yearBirth = bir.get(Calendar.YEAR);
            int monthBirth = bir.get(Calendar.MONTH);
            int dayBirth = bir.get(Calendar.DAY_OF_MONTH);

            age = yearNow - yearBirth;

            if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
                age--;
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return age;
    }


    public static boolean checkExTime(Date date,int days){
        boolean flag = false;
        Date date1 = getDateTime("yyyy-MM-dd",format3.format(new Date()));
        long time1 = date.getTime();
        long time2 = date1.getTime();

        if(time1<=time2){
            long xdays = (time2-time1)/3600/1000/24;
            if(xdays>days){
                flag=true;
            }

        }
        return flag;
    }

    public static boolean checkExTimeByMin(Date date,int min){
        boolean flag = false;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE,min);
        calendar.getTimeInMillis();
        long time1 =  calendar.getTimeInMillis();
        calendar.setTime(new Date());
        calendar.getTimeInMillis();
        long time2 =  calendar.getTimeInMillis();
        if(time1>=time2){
            flag=true;
        }
        return flag;
    }

    public static Date timeToDate(Timestamp timestamp) {

        // Timestamp -> String
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(timestamp);

        // String -> Date
        Date date = new Date();
        //注意format的格式要与日期String的格式相匹配
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;

    }

    public static String timeToDateStr(Timestamp timestamp) {

        // Timestamp -> String
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(timestamp);
        return dateString;

    }

    /**
     * 添加天数
     * @param date
     * @param day
     * @return
     */
    public static Date dateAddDay(Date date, int day) {
        // 号源查询时间往后推一天
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, day);//利用Calendar 实现 Date日期+1天
        return c.getTime();
    }

    public static void main(String[] args) {
        try {
            Date date =  format3.parse("2020-07-30");
           System.out.println(checkExTime(date,5));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
